import axios from 'axios'
import { Modal, message } from 'antd';
// import { baseUrl } from './config.js'
import { notification } from 'antd';
import Router from "umi/router";
const baseUrl = `http://192.168.3.15:19999/`;


const service = axios.create({
  baseURL: baseUrl, // api的base_url
  timeout: 120000, // request timeout 120 s
  withCredentials: true,
});

service.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    const token = sessionStorage.getItem("idToken");
    if (config.url && token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    response.headers['Access-Control-Allow-Credentials'] = 'true';
    response.headers['Access-Control-Allow-Origin'] = baseUrl;
    response.headers['Access-Control-Allow-Origin'] = '*';
    response.headers['Access-Control-Allow-Headers'] =
      'Content-Type, Content-Length, Authorization, Accept, X-Requested-With ';
    response.headers['Access-Control-Allow-Methods'] = 'PUT, POST, GET, DELETE, OPTIONS';

    let res = response.data;

    if (res.retCode - 0 !== 0) {
      notification['warning']({
        message: '请求异常',
        key: res.message,
        description:
          res.message,
      });
    }
    return response.data;
  },

  error => {
    const status = error.response && error.response.status;
    notification['warning']({
      message: '请求异常',
      key: '请求异常',
      description: status === 401 ? '登录已过期，请重新登录' : '数据请求错误，请检查网络!',
    });
    if (status === 401) { // 登录 token 失效
      sessionStorage.clear();
      let tenantUrl = 'default'
      if (localStorage.getItem("tenantUrl")){
        tenantUrl = localStorage.getItem("tenantUrl")
      }
      Router.push(`/user/login?tenantUrl=` + tenantUrl);
    }
    return Promise.reject(error);
  },);

export default service
